package com.utcook.host.fragmentdialog

import androidx.databinding.ObservableArrayList
import androidx.databinding.ObservableBoolean
import androidx.databinding.ObservableField
import androidx.databinding.ObservableInt

class BurnerViewModel {

    val burners = ObservableArrayList<Burner>()
    val selectedBurnerIndex = ObservableInt(0)
    val selectedBurnerName = ObservableField<String>("炉头1")
    val selectedBurnerTemperature = ObservableInt(0)
    val temperatureText = ObservableField<String>("温度: 0°C")
    val timerText = ObservableField<String>("定时: 未设置")
    val startStopButtonText = ObservableField<String>("启动炉头")
    val isRecipeMode = ObservableBoolean(true)
    val recipes = ObservableArrayList<Recipe>()
    val selectedRecipe = ObservableField<Recipe>()
    val burnerCookingStates = ObservableArrayList<BurnerCookingState>()
    
    init {
        loadBurners()
        loadRecipes()
        loadBurnerCookingStates()
        updateSelectedBurner()
    }
    
    private fun loadBurners() {
        burners.clear()
        burners.addAll(listOf(
            Burner("炉头1", false, 0, 0),
            Burner("炉头2", false, 0, 0),
            Burner("炉头3", false, 0, 0),
            Burner("炉头4", false, 0, 0)
        ))
    }
    
    fun selectBurner(index: Int) {
        selectedBurnerIndex.set(index)
        updateSelectedBurner()
        notifyBurnerStateChanged()
    }
    
    private fun updateSelectedBurner() {
        val burner = burners[selectedBurnerIndex.get()]
        selectedBurnerName.set(burner.name)
        selectedBurnerTemperature.set(burner.temperature)
        updateTemperatureText()
        updateTimerText()
        updateStartStopButtonText()
    }
    
    fun setTemperature(temperature: Int) {
        val burner = burners[selectedBurnerIndex.get()]
        burner.temperature = temperature
        selectedBurnerTemperature.set(temperature)
        updateTemperatureText()
        notifyBurnerStateChanged()
    }
    
    fun setTimer(minutes: Int) {
        val burner = burners[selectedBurnerIndex.get()]
        burner.timer = minutes
        updateTimerText()
        notifyBurnerStateChanged()
    }
    
    fun toggleBurner() {
        val burner = burners[selectedBurnerIndex.get()]
        burner.isRunning = !burner.isRunning
        updateStartStopButtonText()
        notifyBurnerStateChanged()
    }
    
    private fun updateTemperatureText() {
        temperatureText.set("温度: ${selectedBurnerTemperature.get()}°C")
    }
    
    private fun updateTimerText() {
        val burner = burners[selectedBurnerIndex.get()]
        if (burner.timer > 0) {
            timerText.set("定时: ${burner.timer}分钟")
        } else {
            timerText.set("定时: 未设置")
        }
    }
    
    private fun updateStartStopButtonText() {
        val burner = burners[selectedBurnerIndex.get()]
        if (burner.isRunning) {
            startStopButtonText.set("停止炉头")
        } else {
            startStopButtonText.set("启动炉头")
        }
    }
    
    private fun notifyBurnerStateChanged() {
        // 通知所有炉头Fragment更新状态
        // 这里可以通过回调或者观察者模式来实现
    }

    fun setRecipeMode(isRecipe: Boolean) {
        isRecipeMode.set(isRecipe)
    }

    private fun loadRecipes() {
        recipes.clear()
        recipes.addAll(listOf(
            Recipe(1, "红烧肉", 45, "中等", "经典红烧肉，肥而不腻", listOf(
                CookingStep(1, "准备五花肉，切成大块", 5),
                CookingStep(2, "锅中放油，爆香姜蒜", 3),
                CookingStep(3, "放入五花肉翻炒", 5),
                CookingStep(4, "加入生抽、老抽调味", 2),
                CookingStep(5, "加入适量清水", 2),
                CookingStep(6, "大火烧开后转小火慢炖", 20),
                CookingStep(7, "炖至肉质软烂即可", 8)
            )),
            Recipe(2, "糖醋里脊", 30, "简单", "酸甜可口的糖醋里脊", listOf(
                CookingStep(1, "里脊肉切成条状", 3),
                CookingStep(2, "加入料酒、盐腌制", 5),
                CookingStep(3, "裹上淀粉", 2),
                CookingStep(4, "锅中放油，炸至金黄", 8),
                CookingStep(5, "锅中留底油，爆香蒜末", 3),
                CookingStep(6, "加入糖醋汁翻炒", 4),
                CookingStep(7, "放入炸好的里脊肉翻炒均匀", 5)
            )),
            Recipe(3, "宫保鸡丁", 25, "简单", "经典川菜宫保鸡丁", listOf(
                CookingStep(1, "鸡胸肉切成丁", 3),
                CookingStep(2, "加入料酒、淀粉腌制", 5),
                CookingStep(3, "锅中放油，爆香干辣椒", 3),
                CookingStep(4, "放入鸡丁翻炒", 6),
                CookingStep(5, "加入花生米", 2),
                CookingStep(6, "加入宫保汁翻炒", 4),
                CookingStep(7, "最后加入葱花即可", 2)
            )),
            Recipe(4, "麻婆豆腐", 20, "简单", "麻辣鲜香的麻婆豆腐", listOf(
                CookingStep(1, "豆腐切成小块", 2),
                CookingStep(2, "锅中放油，爆香豆瓣酱", 3),
                CookingStep(3, "放入肉末翻炒", 4),
                CookingStep(4, "加入豆腐块", 2),
                CookingStep(5, "加入适量清水", 2),
                CookingStep(6, "加入花椒粉调味", 3),
                CookingStep(7, "最后撒上葱花即可", 4)
            )),
            Recipe(5, "水煮鱼", 40, "困难", "鲜嫩麻辣的水煮鱼", listOf(
                CookingStep(1, "鱼片腌制入味", 8),
                CookingStep(2, "锅中放油，爆香辣椒", 4),
                CookingStep(3, "加入豆芽翻炒", 3),
                CookingStep(4, "加入适量清水", 2),
                CookingStep(5, "放入鱼片", 15),
                CookingStep(6, "加入花椒粉调味", 4),
                CookingStep(7, "最后淋上热油即可", 4)
            )),
            Recipe(6, "回锅肉", 35, "中等", "香辣可口的回锅肉", listOf(
                CookingStep(1, "五花肉煮熟切片", 10),
                CookingStep(2, "锅中放油，爆香蒜末", 3),
                CookingStep(3, "放入肉片翻炒", 6),
                CookingStep(4, "加入青椒翻炒", 4),
                CookingStep(5, "加入豆瓣酱调味", 3),
                CookingStep(6, "加入生抽调味", 3),
                CookingStep(7, "最后加入蒜苗即可", 6)
            )),
            Recipe(7, "鱼香肉丝", 25, "中等", "酸甜辣的鱼香肉丝", listOf(
                CookingStep(1, "猪肉切成丝", 3),
                CookingStep(2, "加入料酒、淀粉腌制", 5),
                CookingStep(3, "锅中放油，爆香蒜末", 3),
                CookingStep(4, "放入肉丝翻炒", 6),
                CookingStep(5, "加入木耳丝", 2),
                CookingStep(6, "加入鱼香汁翻炒", 4),
                CookingStep(7, "最后加入葱花即可", 2)
            )),
            Recipe(8, "青椒土豆丝", 15, "简单", "清爽可口的青椒土豆丝", listOf(
                CookingStep(1, "土豆切成丝", 3),
                CookingStep(2, "青椒切成丝", 2),
                CookingStep(3, "锅中放油，爆香蒜末", 3),
                CookingStep(4, "放入土豆丝翻炒", 4),
                CookingStep(5, "加入青椒丝", 1),
                CookingStep(6, "加入盐调味", 1),
                CookingStep(7, "最后加入葱花即可", 1)
            ))
        ))
    }

    fun selectRecipe(recipe: Recipe) {
        android.util.Log.d("BurnerViewModel", "selectRecipe被调用: ${recipe.name}")
        selectedRecipe.set(recipe)
    }
    
    fun startCookingOnBurner(burnerIndex: Int, recipe: Recipe) {
        android.util.Log.d("BurnerViewModel", "startCookingOnBurner: 炉头$burnerIndex, 菜谱: ${recipe.name}")
        if (burnerIndex in 0..3) {
            val cookingState = burnerCookingStates[burnerIndex]
            cookingState.currentRecipe = recipe
            
            // 计算总烹饪时长（所有步骤时长相加）
            val totalDuration = recipe.steps.sumOf { it.duration }
            cookingState.remainingSeconds = totalDuration
            
            android.util.Log.d("BurnerViewModel", "菜谱步骤数量: ${recipe.steps.size}, 第一个步骤: ${recipe.steps.firstOrNull()?.description}")
            
            cookingState.isCooking = true
            cookingState.startCooking()
            android.util.Log.d("BurnerViewModel", "烹饪状态已更新: isCooking=${cookingState.isCooking}, 总时长=${totalDuration}秒, currentStepIndex=${cookingState.currentStepIndex}")
        }
    }
    
    fun getBurnerCookingState(burnerIndex: Int): BurnerCookingState? {
        return if (burnerIndex in 0..3) {
            burnerCookingStates[burnerIndex]
        } else null
    }
    
    fun resetBurnerCookingState(burnerIndex: Int) {
        if (burnerIndex in 0..3) {
            val cookingState = burnerCookingStates[burnerIndex]
            android.util.Log.d("BurnerViewModel", "重置前状态: isCooking=${cookingState.isCooking}, isCompleted=${cookingState.isCompleted}")
            cookingState.reset()
            android.util.Log.d("BurnerViewModel", "重置后状态: isCooking=${cookingState.isCooking}, isCompleted=${cookingState.isCompleted}")
            // 清空选中的菜谱，这样再次点击同一个菜谱时会触发选择事件
            selectedRecipe.set(null)
            android.util.Log.d("BurnerViewModel", "炉头${burnerIndex + 1}烹饪状态已重置，已清空选中菜谱")
        }
    }
    
    fun pauseCookingOnBurner(burnerIndex: Int) {
        if (burnerIndex in 0..3) {
            val cookingState = burnerCookingStates[burnerIndex]
            if (cookingState.isCooking && !cookingState.isPaused) {
                cookingState.pauseCooking()
                android.util.Log.d("BurnerViewModel", "炉头${burnerIndex + 1}烹饪已暂停")
            }
        }
    }
    
    fun resumeCookingOnBurner(burnerIndex: Int) {
        if (burnerIndex in 0..3) {
            val cookingState = burnerCookingStates[burnerIndex]
            if (cookingState.isCooking && cookingState.isPaused) {
                cookingState.resumeCooking()
                android.util.Log.d("BurnerViewModel", "炉头${burnerIndex + 1}烹饪已恢复")
            }
        }
    }
    
    fun togglePauseCookingOnBurner(burnerIndex: Int) {
        if (burnerIndex in 0..3) {
            val cookingState = burnerCookingStates[burnerIndex]
            if (cookingState.isCooking) {
                if (cookingState.isPaused) {
                    resumeCookingOnBurner(burnerIndex)
                } else {
                    pauseCookingOnBurner(burnerIndex)
                }
            }
        }
    }
    
    fun stopCookingOnBurner(burnerIndex: Int) {
        if (burnerIndex in 0..3) {
            val cookingState = burnerCookingStates[burnerIndex]
            if (cookingState.isCooking) {
                cookingState.stopCooking()
                android.util.Log.d("BurnerViewModel", "炉头${burnerIndex + 1}烹饪已结束")
            }
        }
    }
    
    private fun loadBurnerCookingStates() {
        burnerCookingStates.clear()
        for (i in 0..3) {
            burnerCookingStates.add(BurnerCookingState(i))
        }
    }
    
    data class Burner(
        val name: String,
        var isRunning: Boolean,
        var temperature: Int,
        var timer: Int
    ) {
        val statusText: String
            get() = if (isRunning) "运行中" else "待机"
    }
    
    data class BurnerCookingState(
        val burnerIndex: Int,
        var currentRecipe: Recipe? = null,
        var isCooking: Boolean = false,
        var isPaused: Boolean = false,
        var remainingSeconds: Int = 0,
        var isCompleted: Boolean = false,
        var currentStepIndex: Int = 0,
        var currentStepRemainingSeconds: Int = 0
    ) {
        private var countDownTimer: android.os.CountDownTimer? = null
        private var pausedRemainingSeconds: Int = 0
        
        fun startCooking() {
            countDownTimer?.cancel()
            currentStepIndex = 0
            // 设置第一个步骤的剩余时长
            currentStepRemainingSeconds = currentRecipe?.steps?.getOrNull(0)?.duration ?: 2
            isPaused = false
            pausedRemainingSeconds = 0
            
            android.util.Log.d("BurnerCookingState", "开始烹饪: 炉头${burnerIndex + 1}, 总时长=${remainingSeconds}秒, 第一步时长=${currentStepRemainingSeconds}秒")
            startCountDownTimer(remainingSeconds)
        }
        
        private fun startCountDownTimer(seconds: Int) {
            countDownTimer?.cancel()
            countDownTimer = object : android.os.CountDownTimer((seconds * 1000).toLong(), 1000) {
                override fun onTick(millisUntilFinished: Long) {
                    remainingSeconds = (millisUntilFinished / 1000).toInt()
                    
                    // 更新当前步骤倒计时
                    currentStepRemainingSeconds--
                    
                    // 如果当前步骤完成，切换到下一步
                    if (currentStepRemainingSeconds <= 0 && currentStepIndex < (currentRecipe?.steps?.size ?: 0) - 1) {
                        currentStepIndex++
                        currentStepRemainingSeconds = currentRecipe?.steps?.getOrNull(currentStepIndex)?.duration ?: 2
                    }
                }
                
                override fun onFinish() {
                    isCooking = false
                    isPaused = false
                    isCompleted = true
                    remainingSeconds = 0
                    currentStepIndex = 0
                    currentStepRemainingSeconds = 0
                    pausedRemainingSeconds = 0
                }
            }.start()
        }
        
        fun pauseCooking() {
            if (!isPaused && isCooking) {
                isPaused = true
                pausedRemainingSeconds = remainingSeconds
                countDownTimer?.cancel()
                android.util.Log.d("BurnerCookingState", "炉头${burnerIndex + 1}烹饪已暂停，剩余时间: ${pausedRemainingSeconds}秒")
            }
        }
        
        fun resumeCooking() {
            if (isPaused && isCooking) {
                isPaused = false
                val resumeSeconds = pausedRemainingSeconds
                pausedRemainingSeconds = 0
                startCountDownTimer(resumeSeconds)
                android.util.Log.d("BurnerCookingState", "炉头${burnerIndex + 1}烹饪已恢复，剩余时间: ${resumeSeconds}秒")
            }
        }
        
        fun stopCooking() {
            countDownTimer?.cancel()
            isCooking = false
            isPaused = false
            isCompleted = false
            remainingSeconds = 0
            currentStepIndex = 0
            currentStepRemainingSeconds = 0
            pausedRemainingSeconds = 0
            currentRecipe = null
        }
        
        fun reset() {
            stopCooking()
        }
    }
} 